#!/bin/bash

# 安装目录
INSTALL_DIR="$HOME/.deploy-swarm"
BIN_DIR="$HOME/.local/bin"

# 显示安装信息
echo "开始安装 Deploy Swarm..."

# 创建安装目录
echo "创建安装目录..."
mkdir -p "$INSTALL_DIR"/{bin,lib/{dockerfiles,scripts}}
mkdir -p "$BIN_DIR"

# 下载必要文件
echo "下载程序文件..."
# 主程序文件
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/bin/deploy-swarm" -o "$INSTALL_DIR/bin/deploy-swarm"

# 脚本文件
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/scripts/utils.sh" -o "$INSTALL_DIR/lib/scripts/utils.sh"
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/scripts/common.sh" -o "$INSTALL_DIR/lib/scripts/common.sh"
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/scripts/docker.sh" -o "$INSTALL_DIR/lib/scripts/docker.sh"
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/scripts/build.sh" -o "$INSTALL_DIR/lib/scripts/build.sh"
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/scripts/health.sh" -o "$INSTALL_DIR/lib/scripts/health.sh"
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/scripts/deploy.sh" -o "$INSTALL_DIR/lib/scripts/deploy.sh"

# Dockerfile文件
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/dockerfiles/Dockerfile" -o "$INSTALL_DIR/lib/dockerfiles/Dockerfile"
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/dockerfiles/Dockerfile.maven" -o "$INSTALL_DIR/lib/dockerfiles/Dockerfile.maven"
curl -fsSL "https://gitee.com/ai5/deploy-swarm/raw/master/lib/dockerfiles/Dockerfile.gradle" -o "$INSTALL_DIR/lib/dockerfiles/Dockerfile.gradle"

# 创建软链接
echo "创建软链接..."
ln -sf "$INSTALL_DIR/bin/deploy-swarm" "$BIN_DIR/deploy-swarm"

# 设置执行权限
echo "设置文件权限..."
chmod +x "$INSTALL_DIR/bin/deploy-swarm"
chmod +x "$INSTALL_DIR/lib/scripts/"*.sh

# 添加环境变量
SHELL_CONFIG="$HOME/.bashrc"
if [ -n "$ZSH_VERSION" ] || [ -f "$HOME/.zshrc" ]; then
    SHELL_CONFIG="$HOME/.zshrc"
fi

# 添加环境变量到配置文件
if ! grep -q "DEPLOY_SWARM_HOME" "$SHELL_CONFIG"; then
    echo "配置环境变量..."
    echo "" >> "$SHELL_CONFIG"
    echo "# Deploy Swarm Configuration" >> "$SHELL_CONFIG"
    echo "export DEPLOY_SWARM_HOME=\"$INSTALL_DIR\"" >> "$SHELL_CONFIG"
    echo "export PATH=\"\$BIN_DIR:\$PATH\"" >> "$SHELL_CONFIG"
fi

echo "✅ Deploy Swarm 安装完成！"
echo ""
echo "请执行以下命令使环境变量生效："
echo "    source $SHELL_CONFIG"
echo ""
echo "使用说明："

# 加载deploy-swarm脚本并显示帮助信息
source "$INSTALL_DIR/bin/deploy-swarm"
show_usage
